<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/11/17
 * Time: 10:31 AM
 */
declare(strict_types=1);


namespace application\module\admin\controller;

use application\module\admin\addon\Sign as S;
use application\module\admin\addon\rbca\model\UserRoleModel;
use application\module\admin\addon\sign\model\UserModel;
use application\module\admin\addon\sign\throws\PasswordErrorException;
use wshore\core\Redis;
use wshore\core\Response;
use wshore\helper\Validator;
use wshore\throws\DatabaseException;
use wshore\throws\db\RecordNotFoundException;

class user extends admin
{
    /**
     * 用户列表页面
     */
    public function index()
    {
        $this->doLayoutAssign();
        $this->display();
    }

    /**
     * 注册用户
     *
     * 如果用户的邮件已经存在
     * @param string $name
     * @param string $email
     * @param string $password
     * @return void
     */
    public function register(string $name, string $email, string $password)
    {
        if (!trim($email)) Response::failure('电子邮件不能为空');

        try {
            $model = new UserModel($email);
        } catch (RecordNotFoundException $exception) {
            if ($res = Validator::isPasswordInvalid($password)) Response::failure($res);
            if (!trim($name)) Response::failure('姓名不能为空');

            $model = new UserModel();
            $model->nickname = $name;
            $model->email = $email;
            $model->username = $name;
            $model->password = $password;
        }

        try {
            $model->save();
            Response::success('添加成功');
        } catch (DatabaseException $exception) {
            Response::failure('添加出错:' . $exception->getMessage());
        }
    }


    /**
     * 修改密码页面
     */
    public function changepwd()
    {
        $this->doLayoutAssign();
        $this->display();
    }

    public function update()
    {
        if (!empty($_GET['id'])) {
            $id = $_GET['id'];
            unset($_GET['id']);
            $model = new UserModel();
            foreach ($_GET as $k => $v) {
                if ('' === $v or strtolower($v) === 'null') unset($_GET[$k]);
            }
            $rst = $model->update($_GET, ['id' => $id]);
            if ($rst) {
                Response::success('修改成功', $model->find($id));
            } else {
                Response::export([
                    'status' => 0,
                    'message' => '系统出错',
                ]);
            }
        }
        Response::export([
            'status' => 0,
            'message' => '填写的信息不完整',
        ]);
    }

    public function enable($id)
    {
        $model = UserModel::getInstance();
        if ($model->update(['disable' => 0], ['id' => $id])) {
            Response::export([
                'status' => 1,
                'message' => '启用成功',
                'data' => $model->find($id),
            ]);
        } else {
            Response::export([
                'status' => 0,
                'message' => '启用失敗',
            ]);
        }
    }

    public function delete($id)
    {
        $model = UserModel::getInstance();
        $model->beginTransaction();
        if ($model->delete(['id' => $id])) {
            $model->commit();
            Response::export([
                'status' => 1,
                'message' => '禁用成功',
                'data' => $model->find($id),
            ]);

            $rmodel = new UserRoleModel();
            if (false !== $rmodel->delete(['uid' => $id])) {
                $model->commit();
                Response::export([
                    'status' => 1,
                    'message' => '禁用成功',
                    'data' => $model->find($id),
                ]);
            } else {
                $model->rollback();
                Response::export([
                    'status' => 0,
                    'message' => '禁用失败.',
                ]);
            }
        }
        $model->rollback();
        Response::export([
            'status' => 0,
            'message' => '禁用失敗',
        ]);
    }

    /**
     * 禁用账户登录
     * @param $id
     * @return void
     */
    public function disable($id)
    {
        $model = UserModel::getInstance();
        if ($model->update(['disable' => 1], ['id' => $id])) {
            Response::export([
                'status' => 1,
                'message' => '禁用成功',
                'data' => $model->find($id),
            ]);
        }
        Response::export([
            'status' => 0,
            'message' => '禁用失敗',
        ]);
    }

    /**
     * 获取用户列表映射
     * @return void
     */
    public function getMap()
    {
        $list = (array)Redis::getInstance()->getSet('admin.user.map', function () {
            $users = new UserModel();
            return $users->getlist();
        });
        Response::success('OK', $list);
    }


    public function getlist()
    {
        try {
            Response::export([
                'status' => 1,
                'data' => array_values((new UserModel())->getlist()),
            ]);
        } catch (DatabaseException $e) {
            Response::export([
                'status' => 0,
                'message' => '获取列表失败',
            ]);
        }
    }

    public function add()
    {
        $model = UserModel::getInstance();
        if ($model->insert($_GET)) {
            Response::success('添加成功');
        } else {
            Response::failure($model->error());
        }
    }


    /**
     * 修改密码
     * @param string $old_pwd
     * @param string $new_pwd
     * @return void
     */
    public function changePassword(string $old_pwd, string $new_pwd)
    {
        if (S::getInstance()->isPasswordRight($old_pwd)) {
            if (is_numeric($new_pwd)) {
                Response::failure('密码不能全是数字');
            }
            self::$user->password = $new_pwd;
            try {
                if (self::$user->save()) {
                    Response::success('修改成功');
                } else {
                    Response::failure('修改失败：' . self::$user->error());
                }
            } catch (PasswordErrorException $exception) {
                Response::failure('密码过于简单或者不符合要求');
            } catch (\Throwable $e) {
                Response::failure('系统出错:' . $e->getMessage());
            }
        } else {
            Response::failure('修改失败：旧的密码不正确');
        }
    }

}